<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <!-- 1: type   '0' : 表示pid  -->
          <el-button type="primary" size="small" @click="hAdd(1,'0')">添加权限</el-button>
        </div>
        <!-- 如果是用树形结构，需要给 table 指定 row-key -->
        <el-table border :data="permissons" default-expand-all row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <!-- type ：1 表示页面级权限  type：2 表示按钮级权限 -->
              <el-button v-if="row.type === 1" type="text" @click="hAdd(2,row.id)">添加</el-button>
              <el-button type="text" @click="hEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        :visible.sync="showDialog"
        :title="isEdit ? '编辑' : '添加' "
        :is-edit="false"
        @closed="hClosed"
      >
        <!-- 表单内容 -->
        <el-form ref="formData" label-width="100px" :rules="rules" :model="formData">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSubmit()">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addPermission, delPermission, getPermissionDetail, getPermissionList, updatePermission } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const validateName = (rule, value, callback) => {
      let nameList = null
      if (this.isEdit) {
        // 拿到满足条件的第一个值 返回 他的 pid
        const pid = this.newPermissons.find(item => item.id === this.id).pid
        // console.log(pid)
        nameList = this.newPermissons.filter(item => item.pid === pid && item.id !== this.id).map(({ name }) => name.trim())
        // console.log(nameList)
      } else {
        // console.log(this.id)
        nameList = this.newPermissons.filter(item => item.pid === this.id).map(({ name }) => name.trim())
      }
      nameList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    const validateCode = (rule, value, callback) => {
      let codeList = null
      if (this.isEdit) {
        codeList = this.newPermissons.filter(item => item.id !== this.id).map(({ code }) => code)
      } else {
        codeList = this.newPermissons.map(({ code }) => code)
      }
      codeList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      newPermissons: [],
      permissons: [],
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '请输入表述信息', tirgger: 'blur' },
          { validator: validateName, trigger: 'blur' }],
        code: [{ required: true, message: '请输入表述信息', tirgger: 'blur' },
          { validator: validateCode, trigger: 'blur' }],
        description: [{ required: true, message: '请输入表述信息', tirgger: 'blur' }]
      },
      isEdit: false,
      id: ''
    }
  },
  created() {
    this.loadPermissons()
  },
  methods: {
    // 获取权限列表信息
    async  loadPermissons() {
      const res = await getPermissionList()
      // console.log(res)
      // 转成树形结构
      this.newPermissons = res.data.map(({ id, name, pid, code }) => ({ id, name, pid, code }))
      this.permissons = tranListToTreeData(res.data)
      // console.log(this.newPermissons)
    },
    // 添加
    hAdd(type, pid) {
      this.isEdit = false
      this.showDialog = true
      // console.log(type, pid)
      this.formData.type = type
      this.formData.pid = pid
      this.id = pid
    },
    // 提交表单  添加 /   编辑
    async hSubmit() {
      // 兜底
      // 发请求
      try {
        let res = null
        if (this.isEdit) {
          // 保存编辑信息
          res = await updatePermission(this.formData)
        } else {
          res = await addPermission(this.formData)
        }

        // 提醒用户
        this.$message.success(res.message)
        // 关闭 dialog
        this.showDialog = false
        // 渲染
        this.loadPermissons()
      } catch (e) {
        // console.log(e)
        this.$message.error(e.message)
      }
    },
    // 清空表单
    hClosed() {
      // 或者也可以使用 v-if 来重置表单
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 清除表单验证
      this.$refs.formData.resetFields()
    },
    // 删除
    async hDel(id) {
      const result = await this.$confirm('真的要删除吗？呜呜呜~~~', '提示', { type: 'warning' }).catch(e => e)
      if (result !== 'confirm') return
      try {
        const res = await delPermission(id)
        // console.log(res)
        this.$message.success(res.message)
        // 渲染
        this.loadPermissons()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 编辑 数据回填
    async hEdit(id) {
      this.isEdit = true
      this.showDialog = true
      // 数据回填
      const res = await getPermissionDetail(id)
      // console.log(res)
      this.formData = res.data
      // console.log(id)
      this.id = id
    }
  }
}
</script>
